#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
配置文件解析类
"""

__author__ = 'Lei Chen'

import codecs
import configparser
import os

# 默认配置文件
DIR = os.path.split(os.path.realpath(__file__))[0]
_DEFAULT_FILE = os.path.join(DIR, 'api.ini')


class ConfigError(Exception):
    pass


class ApiConfigParser(object):

    def __init__(self, config_file=None):

        _file = config_file or _DEFAULT_FILE

        with open(_file, encoding='UTF-8') as fd:
            data = fd.read()
            if data[:3] == codecs.BOM_UTF8:
                data = data[3:]
                with codecs.openFile(_file, 'w') as file:
                    file.write(data)

        self.cf = configparser.RawConfigParser()
        self.cf.read(_file, encoding='UTF-8')

    def get(self, section, name):
        try:
            return self.cf.get(section, name)
        except Exception:
            return None

    def config(self, system):
        return Config(self, system)

    def projects(self):
        _projects = [{'symbol': symbol, 'name': self.get(symbol, 'name'), 'yaml_dir': self.get(symbol, 'yaml_dir')} for
                     symbol
                     in self.cf.keys() if
                     symbol != 'DEFAULT']
        return _projects


class Config(object):

    def __init__(self, parser, system):
        self.system = system
        self.xdomain = parser.get(system, 'xdomain')
        self.username = parser.get(system, 'username')
        self.password = parser.get(system, 'password')
        self.server_url = parser.get(system, 'url')
        self.token_name = parser.get(system, 'token_name')
        self.accessKey = parser.get(system, 'accessKey')
        self.secretKey = parser.get(system, 'secretKey')
        self.ip = parser.get(system, 'ip')
        self.partnerId = parser.get(system, 'partnerId')
        self.partnerNo = parser.get(system, 'partnerNo')


def main():
    parser = ApiConfigParser()
    # config = Config(parser, 'WEB')
    for item in parser.projects():
        print(item)


if __name__ == '__main__':
    main()
